package ch.zbw.sysventory.server.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.zbw.sysventory.server.model.Printer;
import ch.zbw.sysventory.server.repository.PrinterRepository;
import ch.zbw.sysventory.server.service.PrinterService;

@Service
public class PrinterServiceImpl implements PrinterService {

	@Autowired
	private PrinterRepository printerRepository;

	@Override
	public Printer get(Long id) {
		return this.printerRepository.findOne(id);
	}

	@Override
	public List<Printer> list() {
		return this.printerRepository.findAll();
	}

	@Override
	public Printer save(Printer printer) {
		return this.printerRepository.saveAndFlush(printer);
	}

	@Override
	public Printer update(Printer printer) {
		return this.printerRepository.saveAndFlush(printer);
	}

	@Override
	public Printer createIfNotExists(String name, String driverName, String driverVersion) {
		List<Printer> printerList = this.printerRepository.findByNameAndDriverAndDriverVersion(name, driverName, driverVersion);
		if (printerList.size() > 0) {
			return printerList.get(0);
		} else {
			Printer printer = new Printer();
			printer.setName(name);
			printer.setDriver(driverName);
			printer.setDriverVersion(driverVersion);
			return this.save(printer);
		}
	}

}
